<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-position="center" v-show="showSearch" label-width="90px">
      <!-- <el-form-item label="用户头像" prop="headImages">
        <el-input
          v-model="queryParams.headImages"
          placeholder="请输入用户头像"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="用户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入用户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入用户电话"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="identity">
        <el-input
          v-model="queryParams.identity"
          placeholder="请输入身份证号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户号" prop="tobaccoNumber">
        <el-input
          v-model="queryParams.tobaccoNumber"
          placeholder="请输入商户号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否为商户" prop="permissions">
        <el-select v-model="queryParams.permissions" placeholder="选择是否为商户">
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="区名称" prop="tobaccoArea">
        <el-select v-model="queryParams.tobaccoArea" multiple placeholder="选择区">
          <el-option v-for="(item,index) in regionList" :key="index" :label="item.label" :value="item.label" />
        </el-select>
      </el-form-item>
      <el-form-item style="width:100%">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['member:member:add']"
        >新增</el-button>
      </el-col> -->
      
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['member:member:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入积分模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multipleSelection.length==0"
          @click="handleBigUpdate"
        >批量增减积分</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['member:member:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-input
          v-model="yancaoCode"
          size="mini"
          @input="yancaoCode = yancaoCode.replace(/[^\.\d]/g,'')"
          placeholder="请输入要解绑的烟草证号码"
        ></el-input>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="jiebang"
        >解绑</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
    <!-- <el-table v-loading="loading" :data="memberList"> -->
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <el-table-column label="序号" type="index" :index="(queryParams.pageNum-1)*10+1" />
      <el-table-column label="用户头像" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.headImages" width="50px" height="50px">
          </template>
      </el-table-column>
      <el-table-column label="用户名称" align="center" prop="name" />
      <el-table-column label="店铺名称" align="center" prop="tobaccoName" />
      <el-table-column label="用户电话" align="center" prop="phone" />
      <el-table-column label="身份证号" align="center">
          <template slot-scope="scope">
            <div>{{scope.row.identity?scope.row.identity:'暂未绑定'}}</div>
          </template>
      </el-table-column>
      <el-table-column label="用户总积分" align="center" prop="totalScoring" />
      <el-table-column label="用户未使用积分" align="center" prop="notUsed" />
      <el-table-column label="用过已使用积分" align="center" prop="used" />
      <el-table-column label="是否为商户" align="center">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.permissions" effect="dark" type="success">是</el-tag>
            <el-tag v-else effect="dark" type="danger">否</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="商户号" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.permissions" effect="dark" type="success">{{scope.row.tobaccoNumber}}</div>
            <div v-else effect="dark" type="danger">--</div>
          </template>
      </el-table-column>
      <el-table-column label="商户所属区" align="center" prop="tobaccoArea" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="备注" align="center" prop="remark" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['member:member:edit']"
          >修改</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateIdcard(scope.row)"
            v-hasPermi="['member:member:edit']"
          >编辑身份证号</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-link"
            @click="addYancao(scope.row)"
            v-hasPermi="['member:member:edit']"
          >新增烟草证绑定</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['member:member:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改会员对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户电话" prop="phone">
          <el-input v-model="form.phone" placeholder="用户电话"    @input="form.phone = form.phone.replace(/[^\.\d]/g,'')"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改身份证号 -->
    <el-dialog :close-on-click-modal="false" title="身份证号编辑" :visible.sync="openChangeIdcard" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="身份证号" prop="remark">
          <el-input v-model="form4.identity" placeholder="身份证号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormChangeIdcard">确 定</el-button>
        <el-button @click="openChangeIdcard = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 批量修改积分 -->
    <el-dialog :close-on-click-modal="false" title="批量修改积分" :visible.sync="bigChange" width="500px" append-to-body>
      <el-form ref="form2" :model="form2" :rules="rules2" label-width="80px">
        <el-form-item label="积分" prop="bigJifen">
          <el-input v-model="form2.bigJifen" placeholder="请输入积分" />
        </el-form-item>
        <el-form-item label="积分增减">
            <el-radio v-model="form2.jifenType" :label="1" size="large">增加</el-radio>
            <el-radio v-model="form2.jifenType" :label="2" size="large">减少</el-radio>
          </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="bigChange = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增烟草证绑定 -->
    <el-dialog :close-on-click-modal="false" title="新增烟草证绑定" :visible.sync="addYancaoShow" width="500px" append-to-body>
      <el-form ref="form3" :model="form3" :rules="rules3" label-width="80px">
        <el-form-item label="烟草证号" prop="yancaoCard">
          <el-input v-model="form3.yancaoCard" placeholder="请输入烟草证号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm3">确 定</el-button>
        <el-button @click="addYancaoShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" title="绑定品牌会员卡" v-loading="loading" :visible.sync="showBrand" width="80vw" append-to-body>
      <el-checkbox-group v-model="membershipcardIdList">
        <el-checkbox class="cardCheckBox" v-for="(item,index) in membershipcardList" :key="index" :label="item.id">
          <div class="cardBox">
            <div class="cardName">{{item.name}}</div>
            <el-image
              style="width: 100px; height: 100px"
              :src="item.images"
              fit="cover"
            ></el-image>
          </div>
        </el-checkbox>
      </el-checkbox-group>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="bindingBrand">确 定</el-button>
        <el-button @click="showBrand = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <a href="http://180.76.175.49:7500/member/member/downloadExcel" download="积分模板"><el-link type="primary" style="font-size:12px">下载模板</el-link></a>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addYancao,jiebang,bindingIdcard,getBindingList,binding,changeScore,listMember, getMember, delMember, addMember, updateMember, exportMember } from "@/api/member/member";
import { listMembershipcard } from "@/api/membershipcard/membershipcard";
import { getToken } from "@/utils/auth";

export default {
  name: "Member",
  components: {
  },
  data() {
    var checkAge = (rule, value, callback) => {
      console.log(value)
        if (!value) {
          return callback(new Error('积分不能为空'));
        }
        setTimeout(() => {
          if (!Number.isInteger(value/1)) {
            callback(new Error('请输入数字值'));
          } else {
            if(value/1<=0){
              callback(new Error('请输入大于0的正整数'));
            } else {
              callback()
            }
          }
        }, 0);
      };
    return {
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/member/member/pointsimportexcel"
      },
      openChangeIdcard:false,
      regionList: [
        {
            label: '长春宽城',
            value: 0
        },
        {
            label: '长春德惠',
            value: 1
        },
        {
            label: '长春集团客户',
            value: 2
        },
        {
            label: '长春汽开',
            value: 3
        },
        {
            label: '长春经开',
            value: 4
        },
        {
            label: '长春净月',
            value: 7
        },
        {
            label: '长春绿园',
            value: 9
        },
        {
            label: '长春农安',
            value: 10
        },
        {
            label: '长春九台',
            value: 11
        },
        {
            label: '长春榆树',
            value: 12
        },
        {
            label: '长春高新',
            value: 13
        },
        {
            label: '长春南关',
            value: 14
        },
        {
            label: '长春二道',
            value: 15
        },
        {
            label: '长春双阳',
            value: 16
        },
        {
            label: '长春朝阳',
            value: 17
        },
        {
            label: '长春公主岭',
            value: 18
        },
        {
            label: '长春特业',
            value: 19
        }
      ],
      yancaoCode:'',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员表格数据
      memberList: [],
      membershipcardList:[],//品牌会员卡列表
      membershipcardIdList:[],//品牌会员卡id列表
      multipleSelection:[],
      showBrand:false, // 显示品牌会员卡列表
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        headImages: null,
        name: null,
        totalScoring: null,
        notUsed: null,
        used: null,
        phone:null,
        tobaccoNumber:null,
        tobaccoArea:[],
        permissions:null,
        identity:null
      },
      // 表单参数
      form: {},
      form2: {
        bigJifen:'',
        jifenType:1
      },
      form3: {
        yancaoCard:''
      },
      form4:{
        identity:null
      },
      // 表单校验
      rules:{},
      rules2: {
        bigJifen:[
          { validator: checkAge, trigger: 'change' }
        ]
      },
      rules3: {
        yancaoCard:[
          {required:true,message:'请输入烟草证号',trigger: 'change'}
        ]
      },
      addYancaoShow:false,
      bigChange:false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "积分模板导入";
      this.upload.open = true;
    },
    jiebang(){
      if(this.yancaoCode == ''){
        return
      }
      this.$confirm('是否确认解绑烟草证号 [ '+this.yancaoCode+' ]', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(resOut=> {
          jiebang(this.yancaoCode)
          .then(res=>{
            console.log(res)
            this.msgSuccess("操作成功");
            this.getList()
          })
        })
    },
    addYancao(row){
      this.openId = row.oppenId
      this.form3.yancaoCard = ''
      this.addYancaoShow = true
    },
    /** 查询会员列表 */
    getList() {
      this.loading = true;
      let queryParams = JSON.parse(JSON.stringify(this.queryParams))
      queryParams.tobaccoArea = queryParams.tobaccoArea.join(',')
      if(queryParams.tobaccoArea == ''){
        delete queryParams.tobaccoArea
      }
      listMember(queryParams).then(response => {
        this.memberList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.multipleSelection = []
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        isDelete: null,
        headImages: null,
        name: null,
        totalScoring: null,
        notUsed: null,
        used: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      // let arr = [] // 获取当前页面未选中
      // arr = this.memberList.filter(item=>{
      //   let flag = false
      //   selection.forEach(itemIn => {
      //     if(itemIn.id == item.id){
      //       flag = true
      //     }
      //   });
      //   return !flag
      // })
      // this.multipleSelection = this.multipleSelection.filter(item=>{
      //   let flag = false
      //   this.memberList.forEach(itemIn => {
      //     if(itemIn.id == item.id){
      //       flag = true
      //     }
      //   });
      //   return !flag
      // })
      // this.multipleSelection.push(...selection)
      // console.log(this.multipleSelection)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加会员";
    },
    handleUpdateIdcard(row){
      const id = row.id || this.ids
      this.form4.identity =null
      getMember(id).then(response => {
        this.openId = row.oppenId
        this.form4.identity = row.identity
        this.openChangeIdcard = true;
      });
      
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      console.log(id)
      getMember(id).then(response => {
        this.form = response.data;
        this.form.phone = row.phone
        this.form.remark = row.remark
        this.openId = row.oppenId
        this.open = true;
        this.title = "修改会员";
      });
    },
    /** 批量修改会员积分 */
    handleBigUpdate() {
      this.bigChange = true
    },
    //获取品牌会员列表
    getBrandList(row){
      this.form = row
      // this.membershipcardIdList = row.ttBrandMembershipCardList||[]
      this.loading = true;
      getBindingList(row.id).then(response=>{
        this.showBrand = true
        console.log(response)
        let arr = []
        if(response.data&&response.data.ttBrandMembershipCardList){
          arr = response.data.ttBrandMembershipCardList
        }
        this.membershipcardIdList = arr.map(item=>{
            return item.id+''
          })
        listMembershipcard({
          pageNum: 1,
          pageSize: 1000,
        }).then(response1 => {
          this.membershipcardList = response1.rows.map(item=>{
            item.id = item.id+''
            return item
          });
          this.loading = false;
        }).catch(()=>{
          this.loading = false;
        })
      }).catch(()=>{
        this.loading = false;
      })
      
    },
    bindingBrand(){
      this.loading = true;
      binding({id:this.form.id,cardIds:this.membershipcardIdList}).then(response => {
        this.msgSuccess("修改成功");
        this.loading = false;
        this.showBrand = false;
        this.getList();
      })
      .catch(()=>{
        this.loading = false;
      })
    },
    submitFormChangeIdcard(){
      bindingIdcard({
        openId:this.openId,
        identity:this.form4.identity
      })
      .then(response => {
        console.log(response)
        if(response.data.data){
          this.msgSuccess("修改成功");
          this.openChangeIdcard = false;
          this.getList();
        } else {
          this.$message.error(response.data.msg)
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMember({
              openId:this.openId,
              phone:this.form.phone,
              remark:this.form.remark
            }).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMember(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 批量修改积分
    submitForm2() {
      let arr = []
      this.multipleSelection.forEach(item=>{
        let notUsed = item.notUsed
        let totalScoring = item.totalScoring
        if(this.form2.jifenType == 1){
          totalScoring=this.form2.bigJifen/1+totalScoring
          notUsed=this.form2.bigJifen/1+notUsed
        } else {
          totalScoring = ((totalScoring-this.form2.bigJifen)<0?0:totalScoring-this.form2.bigJifen)
          notUsed = ((notUsed-this.form2.bigJifen)<0?0:notUsed-this.form2.bigJifen)
        }
        arr.push({
          memberId:item.id,
          notUsed,
          used:item.used,
          totalScoring:totalScoring
        })
      })
      this.$refs["form2"].validate(valid => {
        if (valid) {
          changeScore(arr)
          .then(res=>{
            this.msgSuccess("修改成功");
            this.bigChange = false;
            this.getList();
          })
        }
      });
    },
    // 添加烟草证
    submitForm3() {
      this.$refs["form3"].validate(valid => {
        if (valid) {
          addYancao({
            openId:this.openId,
            tobaccoCard:this.form3.yancaoCard
          })
          .then(res=>{
            this.msgSuccess("添加成功");
            this.addYancaoShow = false;
            this.getList();
          })
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除会员编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delMember(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      let queryParams = JSON.parse(JSON.stringify(this.queryParams))
      queryParams.tobaccoArea = queryParams.tobaccoArea.join(',')
      if(queryParams.tobaccoArea == ''){
        delete queryParams.tobaccoArea
      }
      this.$confirm('是否确认导出所有会员数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportMember(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
<style scoped>
.cardCheckBox{
  align-items: flex-start;
}
.cardName{
  width: 100px;
  line-height: 20px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
